(function() {
    'use strict';

    /**
     * @ngdoc directive
     * @name webApp.directive:shop
     * @description
     * # shop
     * 
     */
    angular.module('webApp')
        .directive('itemvalidate', ['dataService', function(dataService) {
            return {
                restrict: 'E',
                template: '<span ng-if="view" class="sui-text-warning"><a href="{{view}}">查看商品</a></span>',
                require: 'ngModel',
                scope: {
                    ngModel: '=',
                    pid: "@",
                },
                controller: ['$templateCache', '$rootScope', '$scope', '$compile', '$timeout', function($templateCache, $rootScope, $scope, $compile, $timeout) {
                    $scope.view = "";
                    console.log("pid", $scope.pid);
                    
                    $scope.$watch('pid', function(newValue, oldValue, scope) {
                        if (newValue && oldValue != newValue) {
                            $scope.pid = newValue;
                            initData();
                            console.log("pid", newValue);
                        }
                    });
                    $scope.$watch('ngModel', function(newValue, oldValue, scope) {
                        if (newValue && oldValue != newValue) {
                            $scope.ngModel = newValue;
                            $scope.view = '#/item/add?id=' + $scope.ngModel;
                            console.log("$scope.ngModel", newValue);
                        }
                    });
                    
                    function initData() {
                        var query = {};
                        if ($scope.pid) {
                            query = { "pid": $scope.pid };
                            dataService.itemGet({ query: query }).then(function(list) {
                                $scope.ngModel = [];
                                console.log("listlistlist", list);
                                if (list.items) {
                                    if (list.items[0]) {
                                        $scope.ngModel = list.items[0].item_id;
                                        $scope.view = '#/item/add?id=' + list.items[0].item_id;
                                    }else{
                                         $scope.ngModel = '';
                                    }
                                }
                            });
                        }
                    }
                    initData();
                }],
                link: function(scope, elem, attrs, ctr) {


                }
            }
        }])
})();
